package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.dto.DeviceDto;
import com.zzyl.nursing.domain.pojo.Device;
import com.zzyl.nursing.domain.vo.DeviceDetailVo;
import com.zzyl.nursing.domain.vo.ProductVo;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2025-05-28
 */
@Service
@RequiredArgsConstructor
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    private final IoTDAClient ioTDAClient;
    @Autowired
    private DeviceMapper deviceMapper;
    private final StringRedisTemplate stringRedisTemplate;

    private final String ALL_PRODUCT_KEY = "iot:all_product";


    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {

        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }



    /**
     * 修改设备
     * 
     * @param dto 设备
     * @return 结果
     */

    @Override
    public int updateDevice(DeviceDto dto) {
        Long countBind = this.lambdaQuery().eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(ObjectUtil.isNotEmpty(dto.getPhysicalLocationType()),Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .count();
        if (countBind>0) {
            throw new BaseException("位置不可重复绑定");
        }

//        UpdateDeviceRequest request = new UpdateDeviceRequest();
//        request.withDeviceId(dto.iotId);
//        UpdateDevice body = new UpdateDevice();
//        body.withDeviceName(dto.getDeviceName());
//        request.withBody(body);
//        UpdateDeviceResponse updateDeviceResponse;
//        try {
//            updateDeviceResponse = ioTDAClient.updateDevice(request);
//            if (updateDeviceResponse.getHttpStatusCode() != 200) {
//                throw new BaseException("修改设备失败");
//            }
//        }catch (Exception e){
//            throw new BaseException("修改设备失败");
//        }
        Device device = BeanUtil.toBean(dto, Device.class);
        this.updateById(device);

        return 1;
    }
    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public List<ProductVo> allProduct() {
        String res = stringRedisTemplate.opsForValue().get(ALL_PRODUCT_KEY);
        return JSONUtil.toList(res,ProductVo.class);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest requset = new ListProductsRequest();
        ListProductsResponse response = ioTDAClient.listProducts(requset);
        if(response.getHttpStatusCode() != 200)
            throw new RuntimeException("获取失败");
        List<ProductSummary> products = response.getProducts();
        stringRedisTemplate.opsForValue().set(ALL_PRODUCT_KEY,JSONUtil.toJsonStr(products));
    }

    @Override
    public void register(DeviceDto dto) {
//        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Device::getDeviceName,dto.getDeviceName());
//        if(count(queryWrapper)>0){
//            throw new BaseException("设备名称已存在，请重新输入");
//        }
//        LambdaQueryWrapper<Device> queryWrapperNodeId = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Device::getNodeId,dto.getDeviceName());
//        if(count(queryWrapperNodeId) > 0){
//            throw new BaseException("设备标识码已存在，请重新输入");
//        }
//        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
//        condition.eq(Device::getBindingLocation,dto.getBindingLocation())
//                .eq(Device::getLocationType,dto.getLocationType())
//                .eq(Device::getProductKey,dto.getProductKey())
//                .eq(Device::getPhysicalLocationType,dto.getPhysicalLocationType());
//        if(count(condition)>0){
//            throw new BaseException("该老人/位置已绑定该产品，请重新输入");
//        }
        Long countDeviceName = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if(countDeviceName>0){
            throw new BaseException("设备名称已存在，请重新输入");
        }
        Long countNodeId = this.lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if(countNodeId>0){
            throw new BaseException("设备标识码已存在，请重新输入");
        }
        Long countBind = this.lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getPhysicalLocationType()),Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .count();
        if(countBind>0){
            throw new BaseException("该老人/位置已绑定该产品，请重新输入");
        }

        //注册到iot

        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(dto.productKey);
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        request.setBody(body);

//        AddDeviceRequest request = new AddDeviceRequest();
//        AddDevice body = new AddDevice();
//        body.withProductId(dto.productKey);
//        body.withDeviceName(dto.getDeviceName());
//        body.withNodeId(dto.getNodeId());
//        request.setBody(body);
        //设置密钥的非一定
//        AuthInfo authInfo = new AuthInfo();
//        String secret = UUID.randomUUID().toString().replaceAll("_", "");
//        authInfo.withSecret(secret.substring(0, 12));
//        body.setAuthInfo(authInfo);
//        AddDeviceResponse response;
//
//        try {
//            response = ioTDAClient.addDevice(request);
//            if (response.getHttpStatusCode() != 200) {
//                throw new ServiceException("iot设备添加失败");
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            throw new BaseException("物联网接口 - 注册设备，调用失败");
//        }
        AddDeviceResponse response = ioTDAClient.addDevice(request);

        if (response.getHttpStatusCode() != 201) {
            throw new ServiceException("iot设备添加失败");
        }

        String secret = response.getAuthInfo().getSecret();
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        device.setPhysicalLocationType(device.getLocationType() == 0? -1:device.getPhysicalLocationType());
        device.setIotId(response.getDeviceId());

        this.save(device);


//        String secret = response.getAuthInfo().getSecret();
//        Device device = BeanUtil.toBean(dto, Device.class);
//        device.setSecret(secret);
//        device.setIotId(response.getDeviceId());

//        try {
//            save(device);
//        }catch (Exception e){
//            throw new BaseException("同一个位置不能绑定同类型的产品");
//        }


    }



//    @Override
//    public DeviceDetailVo queryDeviceDetail(String iotId) {
//        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
//        if(ObjectUtil.isEmpty(device)){
//            return null;
//        }
//        ShowDeviceRequest request = new ShowDeviceRequest();
//        request.setDeviceId(iotId);
//        ShowDeviceResponse response;
//        try {
//            response = ioTDAClient.showDevice(request);
//        }catch (Exception e){
//            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
//        }
//
//        //属性拷贝
//        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);
//
//        deviceVo.setDeviceStatus(response.getStatus());
//        String activeTimeStr = response.getActiveTime();
//        if(StringUtils.isNotEmpty(activeTimeStr)){
//            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
//            //日期时区转换
//            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
//                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
//                    .toLocalDateTime();
//            deviceVo.setActiveTime(activeTime);
//        }
//        return deviceVo;
//    }

    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //查表
        Device device = this.lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        if(ObjectUtil.isEmpty(device)){
            return null;
        }
        //2-iot查询设备
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = ioTDAClient.showDevice(request);
        if(response.getHttpStatusCode() != 200){
            throw new ServiceException("iot设备查询失败");
        }
        //通过响应对象可以获取:active_time,status,product_name

        //关键返回结果
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        String activeTime = response.getActiveTime();
        if (StrUtil.isNotBlank(activeTime)) {
            LocalDateTime beijingTime = Instant.parse(activeTime)
                    .atZone(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setDeviceStatus(response.getStatus());
            deviceDetailVo.setDeviceStatus(response.getStatus());
            deviceDetailVo.setActiveTime(beijingTime);
        }


        return deviceDetailVo;
    }

    @Override
    public int del(String iotId) {
        // 1. 参数校验
        if (ObjectUtil.isEmpty(iotId)) {
            return 1; // 问题点：空参数应视为错误
        }

        // 2. 调用物联网平台API删除
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        ioTDAClient.deleteDevice(request);



        // 4. 删除本地数据库记录
        this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,iotId));

        return 1; // 问题点：固定返回1无法区分操作结果
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //拿到properties对象
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("获取iot平台数据失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollectionUtils.isEmpty(shadow)) {
            throw new BaseException("该设备暂无服务");
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        if (ObjectUtil.isEmpty(reported)){
            throw new BaseException("该设备没有属性");
        }

        LocalDateTime localDateTime = LocalDateTimeUtil.parse(reported.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = localDateTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        ArrayList<Map<String,Object>> mapList = new ArrayList<>();
        jsonObject.forEach((k,v)->{
            Map<String, Object> map = MapUtil.<String, Object>builder()
                    .put("functionId", k)
                    .put("value", v)
                    .put("eventTime", eventTime)
                    .build();
            mapList.add(map);
        });
        return mapList;

//        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
//        request.withDeviceId(iotId);
//        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
//        if(response.getHttpStatusCode() != HttpStatus.SUCCESS){
//            throw new BaseException("调用iot平台失败");
//        }
//        List<DeviceShadowData> shadow = response.getShadow();
//        if (CollUtil.isEmpty(shadow)) {
//            throw new BaseException("获取的设备没有物模型");
//        }
//        DeviceShadowProperties reported = shadow.get(0).getReported();
//        if (ObjectUtil.isEmpty(reported)) {
//            throw new BaseException("该设备没有物模型属性");
//        }
//      //  JSONObject本质是实现了map集合
//        LocalDateTime localDateTime = LocalDateTimeUtil.parse(reported.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
//        LocalDateTime eventTime = localDateTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
//        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
//        ArrayList<Map<String,Object>> mapList = new ArrayList<>();
//        jsonObject.forEach((k,v)->{
//            Map<String, Object> map = MapUtil.<String,Object>builder()
//                     .put("functionId", k)
//                    .put("value", v)
//                    .put("eventTime", eventTime)
//                    .build();
//            mapList.add(map);
//        });
//        //循环遍历properties对象,构建List<Map<String, Object>>
//        return mapList;
    }


    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = ioTDAClient.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
